/*
 * @Author: Drc
 * @Date: 2020-06-11 18:56:32
 * @LastEditors: Drc
 * @LastEditTime: 2020-12-05 19:28:22
 */
import AsyncStorage from '@react-native-community/async-storage'
const TOKEN_KEY = 'TOKEN_KEY'

/**
 * Token管理类
 */
export default class Token {
  static token: string = ''

  //获取token
  static async get() {
    if (this.token) {
      return this.token
    }

    try {
      let storageToken = await AsyncStorage.getItem(TOKEN_KEY)
      if (!storageToken) {
        let newToken = await this.requestToken()
        this.set(newToken)
        this.token = newToken
        return newToken
      }
      this.token = storageToken
      return storageToken
    } catch (error) {
      return error
    }
  }

  //设置token
  static async set(value: string) {
    if (!value) {
      return
    }
    try {
      this.token = value
      await AsyncStorage.setItem(TOKEN_KEY, value)
      console.log('token设置成功:', value)
    } catch (error) {
      console.log('token设置失败:', error)
    }
  }

  //移除token
  static async remove() {
    try {
      this.token = ''
      await AsyncStorage.removeItem(TOKEN_KEY)
      console.log('token移除成功')
    } catch (error) {
      console.log('token移除失败:', error)
    }
  }

  //去服务器请求新token
  static async requestToken() {
    try {
    } catch (error) {
      return error
    }
  }
}
